import { adminList } from "@/services/userProfile";
import UserSession from "@/UserSession";
import { Button, Card, DatePicker, Divider, Form, Menu, Select, Table } from "antd";
import moment from "moment";
import React from "react";
import WorkOrderBaseInfo from "./workOrderBaseInfo";
import { selfBuiltList } from "@/services/aigcUser";
import { workOrderProcessingList, WorkOrderStatisticsBaseInfo, WorkOrderStatisticsList, exportTicketStaticsByCondition } from "@/services/workOrder";
import ProcessingDetail from "../workOrderProcessing/processingDetail";
import { doRobotList } from "@/services/robotManagement";
import { injectIntl } from 'react-intl';

class WorkOrderStatistics extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      userList:[],
      current:1,
      size:10,
      total:0,
      list:[],
      loading:false,
      detail:{},
      processUser:"",
      orderFlag:null,
      applicationList:[]
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
    this.getUserList()
    this.getInfo()
    if(!UserSession.getCurrentUser().isAdmin){
      this.getApplicationList()
    }
  }

  getApplicationList = async () => {
    const res = await doRobotList()
    this.setState({applicationList:res})
  }

  getInfo = () => {
    this.setState({
      loading:true
    },async () => {
      const { current,size,processUser,orderFlag } = this.state;
      const formInfo = this.props.form.getFieldsValue()
      let params = {
        startDate:formInfo.time && formInfo.time[0] ? moment(formInfo.time[0]).format("YYYY-MM-DD") : '',
        endDate:formInfo.time && formInfo.time[1] ? moment(formInfo.time[1]).format("YYYY-MM-DD") : '',
        applicationId:UserSession.getCurrentUser().applicationId ? UserSession.getCurrentUser().applicationId : formInfo.applicationId
      }
      const res1 = await WorkOrderStatisticsBaseInfo({...params,orderFlag:UserSession.getCurrentUser().isAdmin ? 0 : 1})
      const res2 = await WorkOrderStatisticsList({...params,current,size,processUser,orderFlag})
      this.setState({
        loading:false,
        detail:res1,
        list:res2.records,
        total:res2.total
      })
    })
  }

  getUserList = async () => {
    let userList = []
    if(UserSession.getCurrentUser().isAdmin){
      //甲方管理员
      const res = await adminList({current:1,size:999999,applicationId:UserSession.getCurrentUser().applicationId})
      userList =res.records
    }else{
      //乙方
      const res = await selfBuiltList({current:1,size:999999,categoryId:"",name:""})
      userList =res.records
    }
    
    this.setState({userList})
  }

  doSearch = (current,size) => {
    this.setState({current,size},() => {
      this.getInfo()
    })
  }

  doExport = () => {
    const formInfo = this.props.form.getFieldsValue()
    const params = {
        startDate:formInfo.time && formInfo.time[0] ? moment(formInfo.time[0]).format("YYYY-MM-DD") : '',
        endDate:formInfo.time && formInfo.time[1] ? moment(formInfo.time[1]).format("YYYY-MM-DD") : '',
        applicationId:UserSession.getCurrentUser().applicationId ? UserSession.getCurrentUser().applicationId : formInfo.applicationId
    }
    return exportTicketStaticsByCondition(params);
  }

    /**
   * 
   * @param {*} row 表格记录数据
   * @param {*} readonly 是否只读 true只读
   * @param {*} allocatedDisabled 是否禁用分配按钮 true禁用
   * @param {*} replayDisabled 是否禁用回复按钮 true禁用
   */
    openDetail = (row,readonly,allocatedDisabled,replayDisabled) => {
      this.ProcessingDetail.initData(row.id,readonly,allocatedDisabled,replayDisabled)
    }

    setFormInfoToSearch = (obj) => {
      this.setState(obj, () => {
        this.doSearch(1,10)
      })
    }

    renderFilter = (filterParam, menus, type) => (
      <div style={{ textAlign: 'center' }}>
        <Menu onClick={(e) => { filterParam.confirm(); this.setFormInfoToSearch({ [type]: e.key }) }}
          selectedKeys={this.state[type] != null ? [this.state[type]] : []}>
          {menus.map(item => {
            return <Menu.Item key={item.id}>{item.name || item.userName}</Menu.Item>
          })}
        </Menu>
        <Button style={{ margin: "8px" }} size="small" type="primary" ghost onClick={() => { filterParam.confirm(); this.setFormInfoToSearch({ [type]: null }) }}>重置</Button>
      </div>
    )

  render(){
    const { userList,current,size,total,list,loading,detail,applicationList } = this.state;
    const { form:{getFieldDecorator,getFieldValue} } = this.props;
    const { intl } = this.props;
    const columns = [
      {
        title:intl.formatMessage({id:'pages.workOrder.statistics.submitter'}),
        dataIndex:"submitUser",
        width:200
      },
      {
        title:intl.formatMessage({id:'pages.workOrder.statistics.processor'}),
        dataIndex:"orderFlag",
        width:150,
        render:orderFlag => {
          return orderFlag == 0 ? intl.formatMessage({id:'pages.workOrder.statistics.companyOption'}) : intl.formatMessage({id:'pages.workOrder.statistics.serviceOption'})
        },
        filterDropdown: (filterParam) => {
					const menus = [
						{ id: '0', name: intl.formatMessage({id:'pages.workOrder.statistics.companyOption'}) },
						{ id: '1', name: intl.formatMessage({id:'pages.workOrder.statistics.serviceOption'}) },
					];
					return this.renderFilter(filterParam, menus, 'orderFlag');
				},
      },
      {
        title:intl.formatMessage({id:'pages.workOrder.statistics.handler'}),
        dataIndex:"processUser",
        width:200,
        filterDropdown: (filterParam) => {
					return this.renderFilter(filterParam, this.state.userList, 'processUser');
				},
      },
      {
        title:intl.formatMessage({id:'pages.workOrder.statistics.companyName'}),
        dataIndex:"applicationName",
        width:200,
      },
      {
        title:intl.formatMessage({id:'pages.workOrder.statistics.status'}),
        dataIndex:"ticketStatus",
        width:150,
        render:status => {
          return status == 1 ? intl.formatMessage({id:'pages.workOrder.statistics.pending'}) : 
                 status == 2 ? intl.formatMessage({id:'pages.workOrder.statistics.pending'}) : 
                 status == 3 ? intl.formatMessage({id:'pages.workOrder.statistics.processing'}) : 
                 status == 4 ? intl.formatMessage({id:'pages.workOrder.statistics.closed'}) : ''
        }
      },
      {
        title:intl.formatMessage({id:'pages.workOrder.statistics.createTime'}),
        dataIndex:"createTime",
        width:200,
        render:time => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title:intl.formatMessage({id:'pages.workOrder.statistics.closeTime'}),
        dataIndex:"closedTime",
        width:200,
        render:time => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title:intl.formatMessage({id:'pages.workOrder.statistics.resolveDuration'}),
        dataIndex:"solutionDuration",
        width:200
      },
      {
        title:intl.formatMessage({id:'pages.workOrder.statistics.details'}),
        width:100,
        align:"center",
        render:(item,row) => {
          return <Button type="link" onClick={() => this.openDetail(row,true,true,true)}>
            {intl.formatMessage({id:'pages.workOrder.statistics.view'})}
          </Button>
        }
      }
    ]
    return(
      <Card bordered={false} style={{minHeight:"100%"}}>
        <Form layout="inline">
          <Form.Item>
            {getFieldDecorator("time")(
              <DatePicker.RangePicker style={{width:250}} />
            )}
          </Form.Item>
          {
            UserSession.getCurrentUser().isAdmin ? '' : (
              <Form.Item>
                {getFieldDecorator("applicationId")(
                  <Select style={{width:200}} placeholder={intl.formatMessage({id:'pages.workOrder.statistics.selectCompany'})}>
                    <Select.Option value={null}>{intl.formatMessage({id:'pages.workOrder.statistics.allOption'})}</Select.Option>
                    {
                      applicationList.map(item => {
                        return <Select.Option value={item.id}>{item.name}</Select.Option>
                      })
                    }
                  </Select>
                )}
              </Form.Item>
            )
          }
          
          <Form.Item><Button type="primary" onClick={() => this.doSearch(1,size)}> {intl.formatMessage({id:'pages.workOrder.statistics.query'})}</Button></Form.Item>
          <Form.Item><Button type="primary" onClick={() => {this.doExport()}}> {intl.formatMessage({id:'pages.workOrder.statistics.export'})}</Button></Form.Item>
        </Form>

        <Divider />

        <WorkOrderBaseInfo detail={detail} />

        <Divider />

        <Table 
          style={{marginTop:24}}
          dataSource={list}
          loading={loading}
          rowKey={'id'}
          columns={columns}
          scroll={{x:"auto"}}
          pagination={{
            current,
            pageSize:size,
            total,
            showQuickJumper:true,
            onChange:this.doSearch
          }}
        />

        <ProcessingDetail onRef={ref => this.ProcessingDetail = ref} />
      </Card>
    )
  }
}

export default Form.create()(injectIntl(WorkOrderStatistics))
